/**
 * 
 */
package org.easyframework.core.utils;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

/**
 * @ClassName: BeanUtil
 * @Description:
 * @author: daiw
 * @date: 2019年10月17日 下午3:51:37
 */
public class BeanUtil {
	private static Logger logger = LoggerFactory.getLogger(BeanUtil.class);

	/**
	 * entity、DTO转换
	 * 
	 * @param source
	 * @param targetClazz
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static <S, T> T convert(S source, Class<T> targetClazz) {
		Class<?> c = targetClazz;
		T target = null;
		try {
			target = (T) c.newInstance();
		} catch (Exception e) {
			logger.error("数据实体转换异常", e);
		}
		BeanUtils.copyProperties(source, target);
		return target;
	}

	/**
	 * entity、DTO集合转换
	 * 
	 * @param sources
	 * @param targetClazz
	 * @return
	 * @throws Exception
	 */
	public static <S, T> List<T> convertList(List<S> sources, Class<T> targetClazz) {
		List<T> targetList = null;
		try {
			targetList = new ArrayList<>();
			for (S s : sources) {
				targetList.add(convert(s, targetClazz));
			}
		} catch (Exception e) {
			logger.error("数据实体转换异常", e);
		}

		return targetList;
	}
}
